package com.csj.mvvm.algorithm

import android.os.Build
import androidx.annotation.RequiresApi
import java.nio.charset.StandardCharsets
import java.util.*
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec

object TripleDESUtil {

    private const val SECRET = "DESede"
    private const val CIPHER_ALGORITHM = "DESede/ECB/pkcs5padding"

    /**
     * 3DES加密
     * @param str 字符串
     * @param key 密钥（24位密码）
     * @return 加密字符串
     * @throws Exception 异常信息
     */
    @RequiresApi(Build.VERSION_CODES.O)
    @Throws(Exception::class)
    fun encode(str: String, key: String): String {
        val cipher: Cipher = Cipher.getInstance(CIPHER_ALGORITHM)
        val keyBytes: ByteArray = key.toByteArray(StandardCharsets.UTF_8)
        cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(keyBytes, SECRET))
        val doFinal: ByteArray = cipher.doFinal(str.toByteArray(StandardCharsets.UTF_8))
        return Base64.getEncoder().encodeToString(doFinal)
    }

    /**
     * 3DES解密
     * @param str 字符串
     * @param key 密钥（24位密码）
     * @return 解密字符串
     * @throws Exception 异常信息
     */
    @RequiresApi(Build.VERSION_CODES.O)
    @Throws(Exception::class)
    fun decode(str: String?, key: String): String {
        val cipher: Cipher = Cipher.getInstance(CIPHER_ALGORITHM)
        val keyBytes: ByteArray = key.toByteArray(StandardCharsets.UTF_8)
        cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(keyBytes, SECRET))
        val doFinal: ByteArray = cipher.doFinal(Base64.getDecoder().decode(str))
        return String(doFinal)
    }
}